# app/models/debate_models.py
import uuid
from datetime import datetime

import pytz
from sqlmodel import SQLModel, Field, Relationship
from app.models.user_models import User



class DebateSessionBase(SQLModel):
    topic: str
    position: str  # pro / con
    result: str | None = None  # win / lose / draw


class DebateSessionCreate(DebateSessionBase):
    pass


class DebateSessionUpdate(SQLModel):
    topic: str | None = None
    position: str | None = None
    result: str | None = None


class DebateSession(DebateSessionBase, table=True):
    __tablename__ = "debate_sessions"
    id: uuid.UUID = Field(default_factory=uuid.uuid4, primary_key=True)
    user_id: uuid.UUID = Field(foreign_key="users.id", nullable=False)
    created_at: datetime = Field(default_factory=datetime.now)

    user: User | None = Relationship(back_populates="debate_sessions")
    turns: list["DebateTurn"] = Relationship(back_populates="session")
    report: "Report" = Relationship(back_populates="session")



class DebateSessionPublic(DebateSessionBase):
    id: uuid.UUID
    user_id: uuid.UUID
    created_at: datetime = Field(default_factory=datetime.now)



class DebateSessionsPublic(SQLModel):
    data: list[DebateSessionPublic]
    count: int

class DebateTurn(SQLModel, table=True):
    __tablename__ = "debate_turns"
    id: uuid.UUID = Field(default_factory=uuid.uuid4, primary_key=True)
    session_id: uuid.UUID = Field(foreign_key="debate_sessions.id", nullable=False)
    speaker: str  # 'user' or 'ai'
    content: str
    turn_index: int
    timestamp: datetime = Field(default_factory=datetime.now)

    session: DebateSession = Relationship(back_populates="turns")

class DebateTurnCreate(SQLModel):
    session_id: uuid.UUID
    speaker: str
    content: str
    turn_index: int

class DebateTurnPublic(SQLModel):
    id: uuid.UUID
    session_id: uuid.UUID
    speaker: str
    content: str
    turn_index: int
    timestamp: datetime


class Report(SQLModel, table=True):
    __tablename__ = "reports"
    id: uuid.UUID = Field(default_factory=uuid.uuid4, primary_key=True)
    user_id: uuid.UUID = Field(foreign_key="users.id", nullable=False)
    session_id: uuid.UUID = Field(foreign_key="debate_sessions.id", nullable=False)
    score: int
    suggestion: str

    session: DebateSession = Relationship(back_populates="report")
    user: User | None = Relationship()

class ReportCreate(SQLModel):
    session_id: uuid.UUID
    score: int
    suggestion: str

class ReportPublic(SQLModel):
    id: uuid.UUID
    user_id: uuid.UUID
    session_id: uuid.UUID
    score: int
    suggestion: str

class DebateHistoryResponse(SQLModel):
    data: list[DebateSessionPublic]
    count: int

class DebateTurnsResponse(SQLModel):
    data: list[DebateTurnPublic]
    count: int